package com.cbnu.SmartCampusLife;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

@SuppressLint("WorldReadableFiles")
public class TimeTable extends Activity {
	private int LINE = 5;

	String lectureName[][] = new String[15][9];
	String lectureProf[][] = new String[15][9];
	String lectureLoc[][] = new String[15][9];
	String lectureNum[][] = new String[15][9];
	String lecSum[][] = new String[3][12];

	int column = 15;
	int row = 9;

	int lecColor[] = { Color.rgb(134, 175, 220), Color.rgb(232, 184, 184),
			Color.rgb(165, 231, 187), Color.rgb(194, 223, 165), Color.rgb(163, 215, 221),
			Color.rgb(233, 187, 219), Color.rgb(231, 231, 138), Color.rgb(216, 216, 216),
			Color.rgb(231, 225, 203) };

	private LinearLayout outerLayout;
	private TableLayout daysLayout;
	private ScrollView sv;

	private TextView[][] TimeTableTextView;
	private TableRow[] Row;

	int stuIdChk = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_time_table);

		// Check student ID. For Optimize Building name
		try {
			FileInputStream fis = openFileInput("stu_id.txt");
			BufferedInputStream bis = new BufferedInputStream(fis);
			BufferedReader br = new BufferedReader(new InputStreamReader(bis));
			// If student are admitted before 2009-year, then use old building
			// name, else use new building name
			stuIdChk = Integer.parseInt(br.readLine()) < 2009000000 ? 1 : 0;

		} catch (Exception e) {
			;
		}

		// Receive lecture Information from MainMenu Activity
		int x = 0;
		for (int i = 0; i < 15; i++) {
			lectureName[i] = getIntent().getStringArrayExtra("lectureName[" + i + "]");
			lectureProf[i] = getIntent().getStringArrayExtra("lectureProf[" + i + "]");
			lectureLoc[i] = getIntent().getStringArrayExtra("lectureLoc[" + i + "]");
			lectureNum[i] = getIntent().getStringArrayExtra("lectureNum[" + i + "]");
		}
		lecSum[0] = getIntent().getStringArrayExtra("lecSum[0]");
		lecSum[1] = getIntent().getStringArrayExtra("lecSum[1]");
		lecSum[2] = getIntent().getStringArrayExtra("lecSum[2]");
		row = getIntent().getIntExtra("row", 15);
		column = getIntent().getIntExtra("column", 9);

		if (row == 1 && column == 1) {
			int term = getIntent().getIntExtra("term", 0);
			String termStr = null;
			switch (term) {
			case 1:
				termStr = "1";
				break;
			case 2:
				termStr = "하기계정";
				break;
			case 3:
				termStr = "2";
				break;
			case 4:
				termStr = "동기계정";
				break;
			default:
				termStr = null;
				break;
			}
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("개인수업시간표 오류!").setIcon(null).setMessage(termStr + "학기의 수강 과목이 없습니다.")
					.setCancelable(false)
					.setPositiveButton("메인메뉴로 돌아가기", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							// PositiveButton onClick Action
							finish();
						}
					}).show();
		}

		LayoutParams param = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		outerLayout = new LinearLayout(this);
		outerLayout.setOrientation(LinearLayout.VERTICAL);
		outerLayout.setBackgroundColor(Color.BLACK);
		outerLayout.setLayoutParams(param);

		daysLayout = new TableLayout(this);
		daysLayout.setBackgroundColor(Color.WHITE);

		TimeTableTextView = new TextView[row * column][4];
		Row = new TableRow[column];

		for (int i = 0; i < row * column; i++) {
			for (int j = 0; j < 4; j++) {
				TimeTableTextView[i][j] = new TextView(this);
				TimeTableTextView[i][j].setTextColor(Color.BLACK);
				TimeTableTextView[i][j].setGravity(Gravity.CENTER);
			}
		}

		for (int i = 0; i < column; i++) {
			Row[i] = new TableRow(TimeTable.this);
			Row[i].setGravity(Gravity.CENTER);
			Row[i].setBackgroundColor(Color.WHITE);
		}

		x = 0;
		for (int a = 0; a < column; a++) {
			for (int b = 0; b < row; b++) {
				if (lectureName[a][b] == null)
					for (int i = 0; i < 4; i++) {
						TimeTableTextView[x][0].setText(" ");
						TimeTableTextView[x][0].setTextSize(1);
						TimeTableTextView[x][1].setText(" ");
						TimeTableTextView[x][1].setTextSize(1);
						TimeTableTextView[x][2].setText(" ");
						TimeTableTextView[x][2].setTextSize(1);
						TimeTableTextView[x][3].setText(" ");
						TimeTableTextView[x][3].setTextSize(1);
					}
				else if (lectureName[a][b] != null && lectureProf[a][b] == null) {
					TimeTableTextView[x][0].setText(lectureName[a][b]);
					if (a == 0 && b > 0)
						TimeTableTextView[x][0].setTextSize(16);
					else if (x == 0) {
						TimeTableTextView[x][0].setTextSize(10);
						TimeTableTextView[x][0].setText("교\n시");
					} else
						TimeTableTextView[x][0].setTextSize(12);
				} else {
					if (stuIdChk == 0)
						lectureLoc[a][b] = lectureLoc[a][b].replaceAll("\\(.*", "");
					else {
						lectureLoc[a][b] = lectureLoc[a][b].replaceAll(".*\\(", "");
						lectureLoc[a][b] = lectureLoc[a][b].replaceAll("\\)", "");
						lectureLoc[a][b] = lectureLoc[a][b].substring(0, lectureLoc[a][b].length());
					}

					if (lectureName[a][b].length() > LINE) {
						String temp = lectureName[a][b].substring(0, LINE);
						temp += "\n" + lectureName[a][b].substring(LINE);
						TimeTableTextView[x][0].setText(temp);

					} else {
						TimeTableTextView[x][0].setText(lectureName[a][b] + "\n" + " ");
					}
					TimeTableTextView[x][0].setTextSize(10);
					TimeTableTextView[x][1].setText(lectureProf[a][b]);
					TimeTableTextView[x][1].setTextSize(8);
					TimeTableTextView[x][2].setText(lectureNum[a][b]);
					TimeTableTextView[x][2].setTextSize(7);
					TimeTableTextView[x][3].setText(lectureLoc[a][b]);
					TimeTableTextView[x][3].setTextSize(9);

					for (int i = 0; i < 4; i++) {
						for (int j = 0; j < lecSum[0].length; j++) {
							if (lectureName[a][b].equals(lecSum[0][j])) {
								TimeTableTextView[x][i].setBackgroundColor(lecColor[j]);
								break;
							}
						}
					}
				}
				x++;
			}
		}

		x = 0;
		for (int i = 0; i < row * column; i++) {
			LinearLayout ll = new LinearLayout(this);
			ll.setOrientation(1);
			ll.setPadding(-1, -1, -1, -1);
			if (i % row == 0) {
				x++;
				// Row[x-1].setBackgroundColor(Color.rgb(245, 220, 168));
				Row[x - 1].addView(TimeTableTextView[i][0]);
				Log.d("TextView", TimeTableTextView[i][0].getText().toString());
				continue;
			}
			if (x == 1) {
				Row[x - 1].setBackgroundColor(Color.rgb(245, 220, 168));
				Row[x - 1].addView(TimeTableTextView[i][0]);
				Log.d("TextView", TimeTableTextView[i][0].getText().toString());
				continue;

			} else {
				for (int b = 0; b < lecSum[0].length; b++) {
					if (TimeTableTextView[i][0].getText().toString().replaceAll("\n", "")
							.equals(lecSum[0][b])) {
						TimeTableTextView[i][0].setBackgroundColor(lecColor[b]);
						ll.setBackgroundColor(lecColor[b]);
						// For more Readability, if lectures more than 2-time,
						// hide Lecture Info
						if (i >= row
								&& TimeTableTextView[i][0].getText().toString()
										.equals(TimeTableTextView[i - row][0].getText().toString())
								&& TimeTableTextView[i - row][0].getCurrentTextColor() != lecColor[b]) {
							TimeTableTextView[i][0].setTextColor(lecColor[b]);
							TimeTableTextView[i][1].setTextColor(lecColor[b]);
							TimeTableTextView[i][2].setTextColor(lecColor[b]);
							TimeTableTextView[i][3].setTextColor(lecColor[b]);
						}
						break;
					}
				}
			}
			ll.addView(TimeTableTextView[i][0]);
			ll.addView(TimeTableTextView[i][3]);
			ll.addView(TimeTableTextView[i][1]);
			ll.addView(TimeTableTextView[i][2]);
			ll.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					LinearLayout l = (LinearLayout) v;
					String lecLoc = ((TextView) l.getChildAt(0)).getText().toString()
							.replaceAll("\n", "").replaceAll(" ", "")
							+ "\n" + ((TextView) l.getChildAt(1)).getText().toString();
					Log.d("lecLoc", lecLoc);
					Intent intent = new Intent(TimeTable.this, Map.class);
					intent.putExtra("lecLoc", lecLoc);
					intent.putExtra("lecSum[0]", lecSum[0]);
					intent.putExtra("lecSum[1]", lecSum[1]);
					intent.putExtra("lecSum[2]", lecSum[2]);
					if (stuIdChk == 0)
						stuIdChk = 2;
					else if (stuIdChk == 1)
						stuIdChk = 3;
					intent.putExtra("stuIdChk", stuIdChk);
					startActivity(intent);
				}
			});
			Row[x - 1].addView(ll);
		}

		for (int i = 0; i < column; i++)
			daysLayout.addView(Row[i]);

		daysLayout.setStretchAllColumns(true);
		daysLayout.setShrinkAllColumns(true);

		outerLayout.addView(daysLayout);
		sv = (ScrollView) findViewById(R.id.scrollView);
		sv.addView(outerLayout);
	}

	// After first run, FlipView can show TimeTable thumbnail.
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		Thread takeScreenShot = new TakeScreenShot("timeTable.jpg", sv, TimeTable.this);
		takeScreenShot.start();
	}
}